<template>
  <el-card style="height: 80px;">
    <el-form :inline="true" class="form">
      <el-form-item label="角色名称">
        <el-input placeholder="请你输入搜索用户名" v-model="keyword"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="default" :disabled="keyword?false:true" @click="search">搜索</el-button>
        <el-button type="primary" size="default" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card style="margin: 10px 0px;">
    <el-button type="primary" size="default" icon="Plus" @click="addRole">添加职位</el-button>
    <el-table border style="margin: 10px 0px;" :data="allRole">
        <el-table-column type="index" label="#" align="center"></el-table-column>
        <el-table-column  label="id" prop="id" align="center"></el-table-column>
        <el-table-column  label="角色名称" prop="roleName" align="center" show-overflow-tooltip></el-table-column>
        <el-table-column  label="创建时间" prop="createTime" align="center" show-overflow-tooltip></el-table-column>
        <el-table-column  label="更新时间" prop="updateTime" align="center" show-overflow-tooltip></el-table-column>
        <el-table-column  label="操作" width="280px" align="center">
            <template #="{row,$index}">
                <el-button type="primary" size="small" icon="User" @click="setPermission(row)">分配权限</el-button>
                <el-button type="primary" size="small" icon="Edit" @click="updateRole(row)" >编辑</el-button>
                 <el-popconfirm :title="`你确定删除${row.roleName}?`" @confirm="removeRole(row)">
                  <template #reference>
                    <el-button type="primary" size="small" icon="Delete">删除</el-button>
                 </template>
                </el-popconfirm>
            </template>
        </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="pageNo"
      v-model:page-size="pageSize"
      :page-sizes="[5, 10, 15, 20]"
      :background="true"
      layout=" prev, pager, next, jumper,->,sizes,total"
      :total="total"
      @current-change="getHasRole"
      @size-change="sizeChange"
    />
  </el-card>
  <!--添加职位与更新已有的职位的结构：对话框-->
  <el-dialog v-model="dialogVisite" :title="roleParams.id?'更新职位':'添加职位'">
    <el-form :model="roleParams" :rules="rules" ref="form">
        <el-form-item label="职位名称" prop="roleName">
            <el-input v-model="roleParams.roleName" placeholder="请输入职位名称"></el-input>
        </el-form-item>
    </el-form>
    <template #footer>
        <el-button @click="dialogVisite=false">取消</el-button>
        <el-button type="primary" @click="save">确定</el-button>
    </template>
  </el-dialog>
  <!--抽屉组件：分配职位的菜单权限与按钮的权限-->
  <el-drawer v-model="drawer">
    <template #header>
      <h4>分配菜单与按钮的权限</h4>
    </template>
    <template #default>
      <!--树形控件-->
      <el-tree
      ref="tree"
    style="max-width: 600px"
    :data="menuArr"
    show-checkbox
    node-key="id"
    default-expand-all
    :default-checked-keys="selectArr"
    :props="defaultProps"
  />
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click='drawer=false'>取消</el-button>
        <el-button type="primary" @click="handler">确定</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import {ref,onMounted,reactive,nextTick} from 'vue';
import {reqSetPermission ,reqDeleteRole,reqAllRoleList,reqAddOrUpdateRole,reqAllMenuList} from '../../../api/acl/role/index';
import type { MenuList, MenuResponseData,Records,RoleData } from '../../../api/acl/role/type';
import { ElMessage } from 'element-plus';
//当前页码
let pageNo=ref<number>(1)
//一页多少条数据
let pageSize=ref<number>(10)
//搜索职位关键字
let keyword=ref<string>('')
//职位总个数
let total=ref<number>(0)
//存储全部已有的职位
let allRole=ref<Records>([])
//获取form组件实例
let form=ref<any>()
//控制抽屉的显示与隐藏
let drawer=ref<boolean>(false)
//控制对话框的显示与隐藏
let dialogVisite =ref<boolean>(false)
//存储更新与添加职位需要携带的参数
let roleParams = reactive<RoleData>({
    roleName:''
})
//获取tree组件实例
let tree=ref<any>()
//定义数组存储用户权限的数据
let menuArr=ref<MenuList>([])
//组件挂载完毕
onMounted(()=>{
    getHasRole()
})
//准备一个数组：数组用于存储勾选的节点的ID(四级的)
let selectArr=ref<number[]>([])
//获取全部用户信息的方法|分页器当前页码发生变化的回调
let getHasRole=async(pager=1)=>{
    pageNo.value=pager;
   let result = await  reqAllRoleList(pageNo.value,pageSize.value,keyword.value)
   if(result.code==200){
    allRole.value=result.data.records,
    total.value=result.data.total
   }
}
//每页展示数据条数下拉菜单的回调
const sizeChange=()=>{
    getHasRole()
}
//搜索按钮的回调
const search=()=>{
  getHasRole();
}
//重置按钮的回调
const reset=()=>{
    keyword.value='';
    getHasRole()
}
//添加职位按钮的回调
const addRole=()=>{
    //显示出对话框
    dialogVisite.value=true
    //清空数据
    Object.assign(roleParams,{
        roleName:'',
        id:0
    })
    //清空上一次表单校验错误结果
    nextTick(()=>{
       form.value.clearValidate('roleName')
    })

}
//编辑按钮的回调
const updateRole=(row:RoleData)=>{
     //显示出对话框
    dialogVisite.value=true
    Object.assign(roleParams,row)
      //清空上一次表单校验错误结果
      nextTick(()=>{
       form.value.clearValidate('roleName')
    })
}
//自定义校验规则的回调
const validatorRoleName=(rule:any,value:any,callBack:any)=>{
   if(value.trim().length>=2){
    callBack();
   }else{
    callBack(new Error('职位名称至少两位'))
   }
}
//职位相关的校验规则
const rules={
    roleName:[{required:true,trigger:'blur',validator:validatorRoleName}]
}
//确定按钮的回调
const save=async()=>{
    //名单校验结果，结果通过再发请求，结果没通过不发请求
    await form.value.validate();
    let result=await reqAddOrUpdateRole((roleParams as any))
    if(result.code==200){
        ElMessage({type:'success',message:roleParams.id?'更新成功':'添加成功'})
        //对话框关闭
        dialogVisite.value=false;
        //更新数据
        getHasRole(roleParams.id?pageNo.value:1)
    }
}
//删除按钮(确定删除)的回调
const removeRole=async(row:any)=>{
    let result:any=await reqDeleteRole(row.id)
    if(result.code==200){
        ElMessage({
            type:'success',
            message:'删除成功'
        })
        getHasRole(allRole.value.length>1?pageNo.value:pageNo.value-1)
    }
}
//分配权限按钮的回调
const setPermission=async(row:RoleData)=>{
  //抽屉显示出来
  drawer.value=true;
  //收集当前分类权限的职位的数据
  Object.assign(roleParams,row);
  //根据职位获取权限的数据
 let result: MenuResponseData=await reqAllMenuList((roleParams.id as number))
    if(result.code==200){
      menuArr.value=result.data;
      selectArr.value = filterSelectArr(menuArr.value,[]);
    }
}
const filterSelectArr=(allData:any,initArr:any)=>{
  allData.forEach((item:any)=>{
    if(item.select && item.level == 4){
      initArr.push(item.id);
    }
    if(item.children && item.children.length>0){
      filterSelectArr(item.children,initArr)
    }
  })
  return initArr;
}
//树形控件的测试数据
const defaultProps = {
  children: 'children',
  label: 'name',
}
//点击抽屉确定按钮的回调
const handler=()=>{
  //职位的ID
  const roleId = (roleParams.id as number);
  //选中节点的ID
  let arr = tree.value.getCheckedKeys();
  //半选的ID
  let arr1 = tree.value.getHalfCheckedKeys();
  let permissionId =arr.concat(arr1);
  //下发权限
  let result:any=reqSetPermission(roleId,permissionId)
 if(result){
      //抽屉关闭
      drawer.value=false;
    //提示信息
    ElMessage({
      type:'success',
      message:'分配权限成功'
    })
    //页面刷新
    window.location.reload()
 }
}
</script>

<style lang="scss" scoped>
.form{
    height: 50px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}
</style>